package com.hd.manager.shiro;

import com.alibaba.fastjson.JSON;
import com.hd.hdxgddcommon.entity.dto.ResultDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <p>
 * shiro 工具类
 * </p>
 *
 * @author Administrator
 * @since 2018-10-30
 */
@Slf4j
public class ShiroUtils {

    /**
     * 返回 json 格式的 http 响应信息
     *
     * @param response
     * @param result
     */
    public static void responseJson(ServletResponse response, ResultDto result) {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            log.error("http response 发生未知错误...", e);
        } finally {
            out.println(JSON.toJSONString(result));
            out.flush();
            out.close();
        }
    }

    public static String appendPerms(String key) {
        return new StringBuilder("perms[").append(key).append("]").toString();
    }

    /**
     * @param account  账号
     * @param password 密码
     * @return 加密密码
     */
    public static String getEncryptPassword(String account, String password) {
        String hashAlgorithmName = "MD5";
        //加密次数
        int hashIterations = 8;
        //盐值
        ByteSource credentialsSalt = ByteSource.Util.bytes(account);
        Object obj = new SimpleHash(hashAlgorithmName, password, credentialsSalt, hashIterations);
        return obj.toString();
    }
}
